'use strict';

(function (app) {

//创建控制器
    app.register.controller('mqttTestCtrl', ['$scope', '$uibModal', '$log', '$http', '$window', '$rootScope', '$timeout', function ($scope, $uibModal, $log, $http, $window, $rootScope, $timeout) {

        $rootScope.mask = true;


        $scope.returnmsg = "可以使用上述表单发送消息";

        $scope.disstatus = "btn-danger";
        $scope.sublist = {};
        $scope.aa = {};
        $scope.host = "localhost";
        $scope.port = "23142";
        $scope.path = "/mqtt";
        $scope.uid = "";
        $scope.username = "";
        $scope.pwd = "";

        $scope.antServerAuth = 0;
        $scope.clearSession = "1";
        $scope.debug = 1;

        $scope.connected = false;

        $scope.sendpayload = "";
        $scope.topic = "";
        $scope.qos = "0";
        $scope.retain = "0";

        $scope.subqos = "0";
        $scope.subtopic = "";
        $scope.connbtnclass = "btn-warning";

        function loadSgroups() {
            $scope.sgroups = getGroupCfgs();
            $scope.showselect=false
            for (var k in $scope.sgroups) {
                $scope.showselect=true;
                break;
            }
        }
        loadSgroups()


        $scope.changeGroup = function (groupname) {
            $scope.cfgs = getCfgsByGroup(groupname)
        };
        $scope.delCfg=function(cfgid) {
            delCfg(cfgid)
            loadSgroups()
        };
        $scope.changeCfg = function (cfgid) {
            var info = getCfg(cfgid);
            if (!!info) {
                $scope.host = info.host,
                    $scope.port = info.port,
                    $scope.path = info.path,
                    $scope.uid = info.uid,
                    $scope.username = info.username,
                    $scope.pwd = info.pwd,
                    $scope.debug = info.debug,
                    $scope.antServerAuth = info.antServerAuth,
                    $scope.clearSession = info.clearSession,


                    $scope.sendpayload = info.sendpayload,
                    $scope.topic = info.topic,
                    $scope.qos = info.qos,
                    $scope.retain = info.retain,


                    $scope.sublist = info.sublist,
                    $scope.subqos = info.subqos;
                $scope.subtopic = "";
                var s=""
                for (var key in info.sublist) {
                    $scope.subtopic += s+info.sublist[key].topic + ":" + info.sublist[key].qos;
                    s=","
                }

            }


        };

        $scope.sendmsg = function () {
            $rootScope.loading_text = "努力发送中...";
            // console.log($scope.startdate)

            client.send($scope.topic, $scope.sendpayload, $scope.qos * 1, $scope.retain == "1");

        };

        $scope.mqttkey = "";
        function getMqttKey(uid) {
            var channel = "SB";
            $http.post("./api/mqtt/pwd", {
                    name: uid,
                    channel: channel
                })
                .success(function (response) {


                    $scope.mqttkey = response.key;
                });
        }

        $scope.toggleAnimation = function () {
            $scope.animationsEnabled = !$scope.animationsEnabled;
        };
        $scope.saveTo = function (size) {
            $scope.curInfo = {
                host: $scope.host,
                port: $scope.port,
                path: $scope.path,
                uid: $scope.uid,
                username: $scope.username,
                pwd: $scope.pwd,
                debug: $scope.debug,
                antServerAuth: $scope.antServerAuth,
                clearSession: $scope.clearSession,


                sendpayload: $scope.sendpayload,
                topic: $scope.topic,
                qos: $scope.qos,
                retain: $scope.retain,


                sublist: $scope.sublist,
                subqos: $scope.subqos

            };
            var modalInstance = $uibModal.open({
                animation: $scope.animationsEnabled,
                templateUrl: 'saveModalContent.html',
                controller: 'ModalInstanceCtrl',
                size: size,
                resolve: {
                    curInfo: function () {
                        return $scope.curInfo;
                    }
                }
            });

            modalInstance.result.then(function () {
                loadSgroups()
            }, function () {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };
        var client;
        var createClient = function () {
            if (!!!$scope.uid) {
                var aaa = Number(Math.random() * 100000000).toFixed(10);
                $scope.uid = "SB" + aaa;
            }
            client = new Paho.MQTT.Client($scope.host, $scope.port * 1, $scope.path, $scope.uid);
            client.onConnectionLost = onConnectionLost;
            client.onMessageArrived = onMessageArrived;

            client.trace = function (msg) {
                if (!!$scope.debug) {
                    $scope.recvmsg += msg.severity + ":" + "message==>" + msg.message + "\n";
                }
            }

        };

        function onConnect() {
            $timeout(function () {
                $scope.connected = true;
                $scope.recvmsg += $scope.uid + "连接服务器成功!\n"
                $scope.disstatus = "btn-success";
                $scope.connbtnclass = "btn-success"
            }, 10)


        }
        function onConnectionLost(responseObject) {

            $timeout(function () {
                if (responseObject.errorCode !== 0)
                    $scope.recvmsg += "onConnectionLost:" + responseObject.errorMessage + "\n";
                $scope.connected = false;
                $scope.connbtnclass = "btn-warning"
            }, 10)
        }
        function onMessageArrived(message) {

            $timeout(function () {
                if (!!$scope.debug) {
                    $scope.recvmsg += ">>[" + message.destinationName + ":(" + message.qos + "," + message.retained + "," + message.duplicate + ")]" + message.payloadString + "\n";
                } else {

                    $scope.recvmsg += ">>[" + message.destinationName + "]" + message.payloadString + "\n";
                }

            }, 10)
        }
        $scope.disconnect = function () {
            client.disconnect();
            $scope.recvmsg += "连接断开\n";
            $scope.disstatus = "btn-danger"
        };
        $scope.$watch("mqttkey", function (value) {
            if (!!!value) return
            $scope.recvmsg += "开始连接服务\n";
            $scope.pwd = $scope.mqttkey;
            client.connect({
                userName: $scope.username,
                password: $scope.mqttkey,
                onSuccess: onConnect,
                mqttVersion: 4,
                cleanSession: true,
                keepAliveInterval: 60,
                timeout: 600000
            });
        });
        $scope.connect = function () {
            createClient();
            if ($scope.antServerAuth == 1) {
                $scope.username=$scope.uid;
                getMqttKey($scope.uid);
            } else {
                $scope.recvmsg += "开始连接服务\n";
                try {
                    client.connect({
                        userName: $scope.username,
                        password: $scope.pwd,
                        onSuccess: onConnect,
                        mqttVersion: 4,
                        cleanSession: $scope.clearSession == "1",
                        keepAliveInterval: 60,
                        timeout: 600000
                    });
                } catch (e) {
                    $scope.recvmsg += "连接服务器错误：" + e;
                }

            }

        };
        $scope.subscribe = function () {
            if (!!$scope.subtopic) {
                var tmp = $scope.subtopic.split(",");
                for (var i = 0; i < tmp.length; i++) {
                   var  tmps= tmp[i].split(":");
                    if (tmps.length == 1) {
                        subscribe(tmp[i], $scope.subqos);
                    } else if (tmps.length == 2) {
                        subscribe(tmps[0], tmps[1]);

                    }
                }

            } else {
                alert("未设置主题");
            }

        };
        $scope.quicksub = function (topic, qos) {
            if ($scope.aa[topic]) {
                subscribe(topic, qos);
            } else {
                unsubscribe(topic);
            }

        };
        function subscribe(subtopic, qos) {
            if (!!!qos) {
                qos = $scope.subqos;
            }
            if (!!!qos) {
                qos = 0;
            }
            qos = qos * 1;
            client.subscribe(subtopic, {
                qos: qos, invocationContext: {topic: subtopic}, onSuccess: function (obj) {
                    $timeout(function () {
                        $scope.recvmsg += "订阅主题:" + obj.invocationContext.topic + "(" + obj.grantedQos + ")成功!\n"
                        $scope.sublist[subtopic] = {
                            topic: subtopic,
                            qos: obj.grantedQos[0]
                        };

                        $scope.aa[subtopic] = true;
                    }, 10);


                },
                onFailure: function (obj) {
                    $timeout(function () {
                        $scope.recvmsg += "订阅主题:" + obj.invocationContext.topic + "(" + obj.errorCode + ")失败!\n"
                    }, 10);

                }
            });
        }

        function unsubscribe(subtopic) {
            client.unsubscribe(subtopic, {
                invocationContext: {topic: subtopic}, onSuccess: function (obj) {

                    $timeout(function () {
                        $scope.recvmsg += "取消订阅:" + obj.invocationContext.topic + "成功!\n"
                        $scope.aa[subtopic] = false
                    }, 10);


                },
                onFailure: function (obj) {
                    $timeout(function () {

                        $scope.recvmsg += "取消订阅:" + obj.invocationContext.topic + "(" + obj.errorCode + ")失败!\n";
                    }, 10)


                }
            });
        }

        $scope.emptyrecv = function () {
            $scope.recvmsg = "";
        }
    }])
    app.register.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, curInfo) {


        var saveMqttCfgs=getCfgs();
        var maxid = getMaxid();
        $scope.sgroups = getGroups();

        $scope.ok = function () {

            maxid++;
            saveMqttCfgs.push({id: maxid, name: $scope.name, group: $scope.group, info: curInfo});
            window.localStorage.setItem("saveMqttCfgs", JSON.stringify(saveMqttCfgs));
            $uibModalInstance.close($scope.name);
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
        $scope.chggroup = function (elem) {
            $scope.group = elem.g;
        }
    });

    function delCfg(cfgid) {
        var saveMqttCfgs=getCfgs();
        for (var n in saveMqttCfgs) {
            if (saveMqttCfgs[n].id==cfgid) {
                saveMqttCfgs.splice(n,1)
                break;
            }
        }
        window.localStorage.setItem("saveMqttCfgs", JSON.stringify(saveMqttCfgs));
    }
    function getGroupCfgs() {
        var saveMqttCfgs=getCfgs();
        var outgroups={}
        for (var n in saveMqttCfgs) {
            var groupname = saveMqttCfgs[n].group;
            if (!!!outgroups[groupname]) {
                outgroups[groupname] = {group: groupname, cfgs: []};
            }
            outgroups[groupname].cfgs.push(saveMqttCfgs[n])

        }
        return outgroups;
    }

    function getGroups() {
        var saveMqttCfgs=getCfgs();
        var maxid = 0;
        var sgroups = [];
        for (var k in saveMqttCfgs) {
            var tag = false;
            for (var m in  sgroups) {
                if (sgroups[m] == saveMqttCfgs[k].group) {
                    tag = true;
                    break;
                }
            }
            if (tag) {
                continue;
            }
            sgroups.push(saveMqttCfgs[k].group);
        }
        return sgroups;
    }

    function getMaxid() {
        var saveMqttCfgs=getCfgs();
        var maxid = 0;
        var sgroups = [];
        for (var k in saveMqttCfgs) {
            var tag = false;
            for (var m in  sgroups) {
                if (sgroups[m] == saveMqttCfgs[k].group) {
                    tag = true;
                    break;
                }
            }
            if (tag) {
                continue;
            }
            maxid = saveMqttCfgs[k].id > maxid ? saveMqttCfgs[k].id : maxid;
        }
        return maxid;
    }
    function getCfgs() {
        var saveMqttCfgsStr =  window.localStorage.getItem("saveMqttCfgs");
        var saveMqttCfgs=[]
        if (!!saveMqttCfgsStr) {
            saveMqttCfgs=JSON.parse(saveMqttCfgsStr)
        }


        return saveMqttCfgs;
    }
    function getCfgsByGroup(group) {

        var saveMqttCfgs=getCfgs();
        var maxid = 0;
        var cfgs = [];
        for (var k in saveMqttCfgs) {
            if (saveMqttCfgs[k].group == group) {
                cfgs.push(saveMqttCfgs[k]);
            }

        }
        return cfgs;
    }

    function getCfg(cfgid) {
        var saveMqttCfgs=getCfgs()
        if (!!!saveMqttCfgs) {
            return null;
        }

        for (var k in saveMqttCfgs) {
            if (saveMqttCfgs[k].id == cfgid) {
                return saveMqttCfgs[k].info;
            }

        }
        return null;
    }
})(app);


